﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Enum;

public partial class Pages_StateUpdate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string code = Session["code"].ToString();
            State state = new State();
            state.Code = Convert.ToInt32(code);
            StateController Controller = new StateController();
            State returnedState = new State();
            try
            {
                returnedState = Controller.GetState(state);
                if (returnedState != null)
                {
                    txbName.Text = returnedState.Name;
                    txbAcronym.Text = returnedState.Acronym;
                }
            }
            catch (Exception ex)
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento da tela: <br>" + ex.Message +
                                   ".');</script>");
            }
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        State stateUpdate = new State();
        StateController Controller = new StateController();
        try
        {
            if (Controller.UpdateState(populateObject(stateUpdate)) == EnumGenericState.GENERIC_STATE_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Estado Corrigido com Sucesso!');</script>");
                ClearFields();
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a correção, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na correção: <br>" + ex.Message +
                               ".');</script>");
            stateUpdate = null;
        }
        finally
        {
            Response.Redirect("StateMain.aspx");
            Session.Remove("code");
        }

    }

    private State populateObject(State stateUpdate)
    {
        string code = Session["code"].ToString();
        stateUpdate.Code = Convert.ToInt32(code);
        stateUpdate.Name = txbName.Text;
        stateUpdate.Acronym = txbAcronym.Text;
        return stateUpdate;
    }

    public void ClearFields()
    {
        txbAcronym.Text = "";
        txbName.Text = "";
        txbName.Focus();
    }

}